import React, { useState } from 'react';
import {
  Card,
  Table,
  Tag,
  Space,
  Button,
  Typography,
  Tabs,
  Modal,
  Form,
  Input,
  message,
  Tooltip,
} from 'antd';
import {
  CheckCircleOutlined,
  CloseCircleOutlined,
  SendOutlined,
  HourglassOutlined,
  StopOutlined,
} from '@ant-design/icons';

const { Title, Paragraph } = Typography;
const { TabPane } = Tabs;

const initialTradeOrders = [
  {
    key: 'T001',
    type: '组合调仓',
    subject: '稳健增长FOF组合',
    advisor: '张三',
    timestamp: '2024-05-21 10:30',
    status: 'pending',
    details: '为152名客户进行调仓，涉及3只基金。'
  },
  {
    key: 'T002',
    type: '差错处理',
    subject: '客户 王先生 (CUST-007)',
    advisor: '李四',
    timestamp: '2024-05-21 09:45',
    status: 'pending',
    details: '将失败标的"华夏成长混合"替换为"嘉实新兴产业股票"。'
  },
  {
    key: 'T003',
    type: '账户调仓',
    subject: '客户 赵先生 (CUST-113)',
    advisor: '张三',
    timestamp: '2024-05-20 16:20',
    status: 'completed',
    details: '根据独立调仓计划，调整客户持仓权重。'
  },
  {
    key: 'T004',
    type: '组合调仓',
    subject: '全球科技先锋策略',
    advisor: '王五',
    timestamp: '2024-05-20 14:00',
    status: 'rejected',
    rejectReason: '市场波动较大，建议暂缓调仓。'
  },
];

const STORAGE_KEY = 'tradeOrderManagementList';

const TradeOrderManagement = () => {
  const local = localStorage.getItem(STORAGE_KEY);
  const [tradeOrders, setTradeOrders] = useState(local ? JSON.parse(local) : initialTradeOrders);
  const [isRejectModalVisible, setIsRejectModalVisible] = useState(false);
  const [selectedOrder, setSelectedOrder] = useState(null);
  const [form] = Form.useForm();

  const updateOrderStatus = (key, status, rejectReason = '') => {
    setTradeOrders(prevOrders => {
      const newOrders = prevOrders.map(order =>
        order.key === key ? { ...order, status, rejectReason } : order
      );
      localStorage.setItem(STORAGE_KEY, JSON.stringify(newOrders));
      return newOrders;
    });
  };

  const handleApprove = (record) => {
    message.loading({ content: `正在处理交易单 ${record.key}...`, key: record.key });
    setTimeout(() => {
      message.success({ content: `交易单 ${record.key} 已批准并下发执行！`, key: record.key });
      updateOrderStatus(record.key, 'completed');
    }, 1500);
  };
  
  const showRejectModal = (record) => {
    setSelectedOrder(record);
    setIsRejectModalVisible(true);
  };

  const handleRejectSubmit = (values) => {
    message.loading({ content: `正在驳回交易单 ${selectedOrder.key}...`, key: selectedOrder.key });
    setTimeout(() => {
      message.warn({ content: `交易单 ${selectedOrder.key} 已驳回！`, key: selectedOrder.key });
      updateOrderStatus(selectedOrder.key, 'rejected', values.reason);
      setIsRejectModalVisible(false);
      form.resetFields();
    }, 1000);
  };

  const getTagForType = (type) => {
    switch (type) {
      case '组合调仓': return <Tag color="blue">{type}</Tag>;
      case '差错处理': return <Tag color="orange">{type}</Tag>;
      case '账户调仓': return <Tag color="purple">{type}</Tag>;
      default: return <Tag>{type}</Tag>;
    }
  };

  const columns = [
    { title: '交易单号', dataIndex: 'key', key: 'key' },
    { title: '类型', dataIndex: 'type', key: 'type', render: getTagForType },
    { title: '主题', dataIndex: 'subject', key: 'subject' },
    { title: '提交人', dataIndex: 'advisor', key: 'advisor' },
    { title: '提交时间', dataIndex: 'timestamp', key: 'timestamp' },
    { title: '详情', dataIndex: 'details', key: 'details' },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        record.status === 'pending' && (
          <Space size="middle">
            <Button icon={<CheckCircleOutlined />} type="primary" onClick={() => handleApprove(record)}>
              一键下单
            </Button>
            <Button icon={<CloseCircleOutlined />} type="primary" danger onClick={() => showRejectModal(record)}>
              一键驳回
            </Button>
          </Space>
        )
      ),
    },
  ];

  const renderTable = (status) => (
    <Table
      dataSource={tradeOrders.filter(o => o.status === status)}
      columns={columns.filter(c => c.key !== 'action' || status === 'pending')}
      rowKey="key"
      pagination={{ pageSize: 5 }}
      expandable={status === 'rejected' ? {
        expandedRowRender: record => <p style={{ margin: 0 }}>驳回原因: {record.rejectReason}</p>,
        rowExpandable: record => record.rejectReason,
      } : undefined}
    />
  );

  return (
    <div style={{ padding: '24px' }}>
      <Title level={3}>交易单管理</Title>
      <Paragraph type="secondary">
        交易员工作台。在此审核、执行或驳回由投顾下发的各类交易指令。
      </Paragraph>

      <Card>
        <Tabs defaultActiveKey="pending">
          <TabPane
            tab={<span><HourglassOutlined /> 待处理</span>}
            key="pending"
          >
            {renderTable('pending')}
          </TabPane>
          <TabPane
            tab={<span><StopOutlined /> 已驳回</span>}
            key="rejected"
          >
            {renderTable('rejected')}
          </TabPane>
          <TabPane
            tab={<span><SendOutlined /> 已处理</span>}
            key="completed"
          >
            {renderTable('completed')}
          </TabPane>
        </Tabs>
      </Card>

      <Modal
        title="驳回交易单"
        open={isRejectModalVisible}
        onCancel={() => setIsRejectModalVisible(false)}
        footer={null}
      >
        <Form form={form} onFinish={handleRejectSubmit} layout="vertical">
          <Paragraph>
            您正在驳回交易单 <strong>{selectedOrder?.key}</strong>。请输入驳回原因，将通知给提交人。
          </Paragraph>
          <Form.Item
            name="reason"
            label="驳回原因"
            rules={[{ required: true, message: '必须填写驳回原因' }]}
          >
            <Input.TextArea rows={4} placeholder="例如：市场波动较大，建议暂缓调仓。"/>
          </Form.Item>
          <Form.Item style={{textAlign: 'right', marginBottom: 0}}>
            <Button onClick={() => setIsRejectModalVisible(false)} style={{marginRight: 8}}>
              取消
            </Button>
            <Button type="primary" danger htmlType="submit">
              确认驳回
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default TradeOrderManagement;